package server

import (
	"encoding/json"
	"net/http"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

var MarshalOptions = protojson.MarshalOptions{
	EmitUnpopulated: true,
	UseProtoNames:   true,
}

type JsonEncoder struct {
}

func (j JsonEncoder) Marshal(v interface{}) ([]byte, error) {
	if m, ok := v.(proto.Message); ok {
		return MarshalOptions.Marshal(m)
	}
	return json.Marshal(v)
}

func (j JsonEncoder) Unmarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}

func (j JsonEncoder) Name() string {
	return "json"
}

// MyResponseEncoder 根据proto tag name解析响应请求
func MyResponseEncoder(w http.ResponseWriter, r *http.Request, v interface{}) error {
	myCode := JsonEncoder{}
	data, err := myCode.Marshal(v)
	if err != nil {
		return err
	}
	codeName := myCode.Name()
	if contentType := r.Header.Get("Content-Type"); contentType != "" {
		codeName = contentType
	}
	w.Header().Set("Content-Type", "application/"+codeName+";charset=UTF-8")
	w.Write(data)
	return nil
}
